<?php 
namespace app\mall\controller;
use controller\BasicAdmin;
use service\DataService;
use think\Db;
use think\Request;
use app\mall\model\GoodsSpec as GoodsSpecModel;
use app\mall\model\GoodsSpecDetail as GoodsSpecDetailModel;
class Goodsspec extends BasicAdmin{
	/**
	 * 商品属性维护
	 * @Author   lingyun
	 * @DateTime 2017-11-30T19:31:20+0800
	 * @return   [type]                   [description]
	 */
	public function index(){
		$id = input('id');		//商品id
		$goods = Db::name('goods')->where('id',$id)->field('id,name,is_spec,addtime')->find();
		$goods_price = Db::name('goods_spec_detail')->where(['goods_id'=>$id,'is_deleted'=>0])->find();
		$spec = Db::name('goods_spec_name')->where('is_deleted',0)->field('id,name,addtime')->select();		//商品属性
		$this->assign('goods',$goods);
		$this->assign('goods_price',$goods_price);
		$this->assign('spec',$spec);
		$this->assign('title','商品属性');
		$this->assign('id',$id);
		return $this->fetch('index');
	}
	/**
	 * 保存属性名称
	 * @Author   lingyun
	 * @DateTime 2017-11-30T21:13:12+0800
	 */
	public function addspeccate(){		//从第6条开始往下
		$post = input('post.');
		$data = $this->toArray($post);		//生成保存到数据表goods_spce表的数据
		Db::name('goods_spec')->where('goods_id',$post['goods_id'])->update(['is_deleted'=>1]);
		$arr = array();
		foreach($data as $k => $v){
			$goodsspecmodel = new GoodsSpecModel();
			$res = $goodsspecmodel->save($v);
			$data[$k]['specs'] = $goodsspecmodel->id;
			array_push($arr,$data[$k]);	
		}
		$html = $this->toArrayKey($arr);
		$this->success($html,'');
	}
	/**
	 * 保存属性的具体信息  (价格、安全库存)  
	 * @Author   lingyun
	 * @DateTime 2017-12-01T11:29:22+0800
	 * @return   [type]                   [description]
	 */
	public function savespecdetail(){
		$posts = input('post.');
		if($posts['sign'] == 1){		//有属性
			Db::name('goods_spec_detail')->where('goods_id',$posts['goods_id'])->update(['is_deleted'=>1]);		//将原先的属性设置为无效    
			$data = $this->toComArr($posts);	
			$model = new GoodsSpecDetailModel();
			$res = $model->saveall($data);
			$root = request()->domain();		//网站根目录
			$url = "/mall/goods/goods.html";		///index.php/mall/goodsspec/index.html?id=2
			if($res !== false){
				Db::name('goods')->where('id',$posts['goods_id'])->update(['is_spec'=>1]);		//更新商品属性
			}
		}else{		//无属性
			if(!empty($posts['goods_spec_id'])){
				$res = Db::name('goods_spec_detail')->where('id',$posts['goods_spec_id'])->update(['price'=>$posts['n_price'],'member_price'=>$posts['member_price'],'warn_stock'=>$posts['n_warn_stock']]);
			}else{
				$res = Db::name('goods_spec_detail')->insertGetId(['goods_id'=>$posts['goods_id'],'price'=>$posts['n_price'],'member_price'=>$posts['member_price'],'warn_stock'=>$posts['n_warn_stock'],'specs'=>0,'addtime'=>time()]);
			}
		}
		$res!==false?$this->success('保存成功',url('@admin').'#'.url('Goods/goods').'?spm='.input('spm')):$this->error('保存失败','');
	}
	/**
	 * 编辑属性
	 * @Author   lingyun
	 * @DateTime 2017-12-01T14:34:03+0800
	 * @return   [type]                   [description]
	 */
	public function edit_spec(){
		$goods_id = input('id');		//商品ID
		$goods = Db::name('goods')->where('id',$goods_id)->find();		//商品详情
		$goods_price = Db::name('goods_spec_detail')->where(['goods_id'=>$goods_id,'specs'=>0])->find();
		$goods_spec_name = Db::name('goods_spec_name')->select();
		$goods_spec = Db::name('goods_spec')->where(['goods_id'=>$goods_id,'is_deleted'=>0])->field('id,spec_id,detail')->order('id asc')->select();
		$goods_spec_detail = Db::name('goods_spec_detail')->where(['goods_id'=>$goods_id,'is_deleted'=>0])->field('id,title,price,member_price,score,warn_stock,specs')->select();
		$this->assign('id',$goods_id);
		$this->assign('goods',$goods);
		$this->assign('goods_spec_name',$goods_spec_name);		//属性分类
		$this->assign('goods_spec',$goods_spec);				//属性名称
		$this->assign('goods_price',$goods_price);
		$this->assign('goods_spec_detail',$goods_spec_detail);	//属性详情
		$this->assign('title','商品属性');
		return $this->fetch('edit_spec');
	}
	/**
	 * 删除商品的属性名称（分类），成新生成属性规则组合
	 * @return [type]
	 */
	public function delspec(){
		$post = input('post.');		//接受的数据
		$res = Db::name('goods_spec')->where('id',$post['id'])->update(['is_deleted'=>1]);		//删除商品的属性名称

        $sql = "UPDATE ys_goods_spec_detail SET is_deleted=1 WHERE find_in_set(".$post['id'].",specs) AND goods_id=".$post['goods_id'];
        Db::query($sql);

        $res!==false?$this->success('删除成功',''):$this->error('删除失败','');
//		if($res>0){
//			$spec = Db::name('goods_spec')->alias('a')->join('ys_goods_spec_name b','a.spec_id=b.id','LEFT')->where(['a.goods_id'=>$post['goods_id'],'a.is_deleted'=>0])->field('a.id as specs,a.spec_id,a.goods_id,a.detail,a.addtime,concat(b.name,": ",a.detail) as title')->select();		//商品属性名称
//			$html = $this->toArrayKey($spec);		//生成html
//			$this->success($html,'');				//最终生成的商品属性html
//		}else{
//			$this->error('保存失败','');
//		}
	}

	/**
	 * 删除相应的数据
	 * @Author   lingyun
	 * @DateTime 2017-12-01T15:07:26+0800
	 * @return   [type]                   [description]
	 */
	public function del(){
		$post = input('post.');
		$res = Db::name($post['database'])->where('id',$post['id'])->update(['is_deleted'=>1]);
		$res>0?$this->success('删除成功',''):$this->error('删除失败','');
	}
	/**
	 * 修改属性详情的值
	 * @Author   lingyun
	 * @DateTime 2017-12-01T15:44:10+0800
	 * @return   [type]                   [description]
	 */
	public function saveval(){
		$post = input('post.');
		$res = Db::name('goods_spec_detail')->where('id',$post['id'])->update([$post['field']=>$post['val']]);
		$res!==false?$this->success('保存成功',''):$this->error('保存失败','');
	}
	/**
	 * 修改属性名称，在原先的基础上修改属性名称，不需要删除原先的属性
	 * @Author   lingyun
	 * @DateTime 2017-12-01T16:03:52+0800
	 * @return   [type]                   [description]
	 */
	public function savespec(){
		$post = input('post.');
		$spec_name = Db::name('goods_spec')->where('id',$post['id'])->value('detail');		//商品属性名称
		$sql = "UPDATE ys_goods_spec_detail SET title=REPLACE(title,'".$spec_name."','".$post['val']."') WHERE goods_id=".$post['goods_id']." AND is_deleted=0";		//将原先的属性名称替换成新修改的属性名称
		$res = Db::query($sql);		//替换属性名称
		$res = Db::name('goods_spec')->where('id',$post['id'])->update(['detail'=>$post['val']]);
		$res!==false?$this->success('修改成功','',['spec_name'=>$spec_name]):$this->error('修改失败','',['spec_name'=>$spec_name]);
		// Db::name('goods_spec')->where('id',$post['id'])->update(['is_deleted'=>1]);
		// $spec = Db::name('goods_spec')->where('id',$post['id'])
		// $kid = Db::name('goods_spec')->insertGetId(['spec_id'=>$spec['id']]);		//新增记录数据
		// $spec = Db::name('goods_spec')->where(['goods_id'=>$post['goods_id'],'is_deleted'=>0])->field('id,goods_id,detail')->select();		//属性分类名称
		// $html = $this->toArrayKey('');
	}
	/**
	 * 添加 -- 保存到
	 * @Author   lingyun
	 * @DateTime 2017-11-30T21:22:17+0800
	 * @return   [type]                   [description]
	 */
	private function toArray($post){
		$goods_id = $post['goods_id'];
		$spec_id = $post['spec_id'];		//属性id
		$spec_name = $post['spec_name'];	//具体的属性名称
		$dikaer = array();		//迪笛卡尔积，进行排列组合的数据
		foreach($spec_id as $k => $v){
			// if(!array_key_exists($v,$dikaer)){
			// 	$dikaer[$v] = array();
			// }
			// $arr = array('goods_id'=>$goods_id,'title'=>$post['title'][$k],'spec_id'=>$post['spec_id'][$k],'detail'=>$post['spec_name'][$k]);
			// array_push($dikaer[$v],$arr);		//组合笛卡尔数组
			$res[$k]['goods_id'] = $goods_id;
			$res[$k]['detail'] = $spec_name[$k];
			$res[$k]['title'] = $post['title'][$k];
			$res[$k]['addtime'] = time();
			$res[$k]['spec_id'] = $spec_id[$k]; 
		}
		// $data[0] = $res;
		// $data[1] = $dikaer;
		return $res;		//属性入库数据，以及属性组合数组
	}
	/**
	 * 获取主键进行数据组合
	 * @Author   lingyun
	 * @DateTime 2017-12-01T10:40:50+0800
	 * @return   [type]                   [description]
	 */
	private function toArrayKey($data){
		$c_dikaer = array();		//迪笛卡尔积，进行排列组合的数据
		$html = '';
		foreach($data as $k => $v){
			if(!array_key_exists($v['spec_id'],$c_dikaer)){
				$c_dikaer[$v['spec_id']] = array();
			}
			unset($data[$k]['detail']);
			unset($data[$k]['goods_id']);
			unset($data[$k]['addtime']);
			unset($data[$k]['spec_id']);
			array_push($c_dikaer[$v['spec_id']],$data[$k]);		//组合笛卡尔数组
		}
		$r_dikaer = dikaerr($c_dikaer);

		foreach($r_dikaer as $kk => $vv){
			if(is_array($vv['specs'])){
				$r_dikaer[$kk]['specs'] = sort($vv['specs']);
			}
			$title = is_array($vv['title'])?implode('  ',$vv['title']):$vv['title'];
			$specs = is_array($vv['specs'])?implode(',',$vv['specs']):$vv['specs'];
			$html .= '<div class="layui-form-item"><div class="layui-inline"><div class="layui-input-inline"><input type="text" name="title[]" required="required" readonly="readonly" placeholder="" autocomplete="off" class="layui-input" value="'.$title.'"></div></div><div class="layui-inline"><div class="layui-input-inline" ><input type="text" name="price[]" required="required" placeholder="请输入属性价格" autocomplete="off" class="layui-input" value=""></div></div><div class="layui-inline"><div class="layui-input-inline" ><input type="text" name="member_price[]" required="required" placeholder="请输入会员价格" autocomplete="off" class="layui-input" value=""></div></div><div class="layui-inline"><div class="layui-input-inline" ><input type="text" name="warn_stock[]" required="required" placeholder="请输入安全库存" autocomplete="off" class="layui-input" value=""></div></div><input type="hidden" name="specs[]" value="'.$specs.'"><span class="layui-btn tianjiayihan" type="btn" onclick="reduce(this);">移除</span></div>';
		}
		return $html;
	}
	/**
	 * 排列组合
	 * @Author   lingyun
	 * @DateTime 2017-12-01T09:54:00+0800
	 * @param  $data  需要进行排列组合的数组   
	 * @param  $cate  属性的分类
 	 * @return   [type]                   [description]
	 */
	private function toComArr($data){
		foreach($data['specs'] as $k => $v){
			if(isset($data['id'][$k])){
				$res[$k]['id'] = $data['id'][$k];
			}
			$res[$k]['goods_id'] = $data['goods_id'];
			$res[$k]['specs'] = $v;
			$res[$k]['warn_stock'] = $data['warn_stock'][$k];		//安全库存
			$res[$k]['title'] = $data['title'][$k];
			$res[$k]['price'] = $data['price'][$k];
			$res[$k]['member_price'] = $data['member_price'][$k];
			$res[$k]['is_deleted'] = 0;
			// $res[$k]['score'] = $data['score'][$k];
			$res[$k]['addtime'] = time();
		}
		return $res;
	}	

}
